package com.oracle.coherence.patterns.security.accesscontrol;

import com.tangosol.run.xml.XmlElement;
import com.tangosol.run.xml.XmlHelper;
import com.tangosol.util.Base;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * An implementation of {@link XmlPermissionsChecker} that reads its permissions
 * from an XML file the name of which is passed as a constructor argument.
 * <p/>
 *
 * @author Jonathan Knight
 */
public class FilePermissionsChecker extends XmlPermissionsChecker {

    /**
     * Create a new instance of a FilePermissionsChecker using the specified
     * permissions file name.<p/>
     * To locate the permissions file the name is first treated as a normal file name.
     * If no file with this name exists the classpath is searched for a matching
     * resource.
     *
     * @param permissionsFilename - the name of the permissions file to use.
     */
    public FilePermissionsChecker(String permissionsFilename) {
        this(permissionsFilename, Boolean.toString(true));
    }

    /**
     * Create a new instance of a FilePermissionsChecker using the specified
     * permissions file name.<p/>
     * To locate the permissions file the name is first treated as a normal file name.
     * If no file with this name exists the classpath is searched for a matching
     * resource.
     *
     * @param permissionsFilename - the name of the permissions file to use.
     * @param allowLocal          - a bollean string to indicate whether local principals
     *                            are authorised or not.
     */
    public FilePermissionsChecker(String permissionsFilename, String allowLocal) {
        super(Boolean.parseBoolean(allowLocal));
        init(permissionsFilename);
    }

    public void init(String permissionsUrl) {
        if (permissionsUrl == null || permissionsUrl.length() == 0) {
            throw new IllegalArgumentException("The permissions file name cannot be null");
        }

        URL url;
        if (permissionsUrl.toLowerCase().startsWith("classpath://")) {
            permissionsUrl = permissionsUrl.substring(11);
            url = getClass().getResource(permissionsUrl);
        } else {
            try {
                url = new URL(permissionsUrl);
            } catch (MalformedURLException e) {
                throw Base.ensureRuntimeException(e, "Error opening permissions URL " + permissionsUrl);
            }
        }

        XmlElement xmlPermissions = XmlHelper.loadXml(url);
        setXmlPermissions(xmlPermissions);
    }

}
